/**
 * Name:ajax.js
 * Author:gene.jiang
 * E-mail:1013195469@qq.com
 * Website:http://www.jianggujin.com/
 * LICENSE:Apache v2 License
 * Description:扩展jQuery的ajax请求(http://www.jianggujin.com)，为jQuery的ajax方法增加成功方法与错误方法的拦截方法，在原有ajax参数基础上新增beforeSuccess、beforeError、afterRemote三个方法，分别用于成功方法前置拦截、错误方法前置拦截、请求完成方法（不论成功失败，都会执行）
 */
layui.define(['jquery'], function(exports) {
    var $ = jQuery = layui.jquery;
    "use strict";
    var _remote = $.ajax;
    /**
     * ajax请求，参数与jQuery.ajax基本相同，在其原有参数基础上增加beforeSuccess、beforeError、afterRemote三分方法
     */
    function remote(url, options) {
        if(typeof url === "object") {
            options = url;
            url = undefined;
        }
        options = options || {};
        if(typeof url === "string") {
            options.url = url;
        }
        var success = options.success,
            error = options.error;
        options.success = function(data, status, xhr) {
            var that = this,
                notIntercept = true,
                args = [].slice.call(arguments, 0),
                ref = {
                    data: args[0]
                };
            //成功前置处理
            if(typeof this.beforeSuccess == 'function') {
                args[0] = ref;
                notIntercept = this.beforeSuccess.apply(that, args);
                args[0] = ref.data;
            }
            //执行真正的成功处理
            if(notIntercept !== false && typeof success == 'function') {
                success.apply(that, args);
            }
            //成功后置处理
            if(typeof this.afterRemote == 'function') {
                var param = [true, !!notIntercept];
                param.push(args);
                param.push(xhr);
                this.afterRemote.apply(that, param);
            }
        };
        options.error = function(xhr, errorType, error) {
            var that = this,
                notIntercept = true,
                args = [].slice.call(arguments, 0);
            //失败前置处理
            if(typeof this.beforeError == 'function') {
                notIntercept = this.beforeError.apply(that, args);
            }
            //执行真正的失败处理
            if(notIntercept !== false && typeof error == 'function') {
                error.apply(that, args);
            }
            //失败后置处理
            if(typeof this.afterRemote == 'function') {
                var param = [false, notIntercept];
                param.push(args);
                param.push(xhr);
                this.afterRemote.apply(that, param);
            }
        };
        _remote(options);
    };
    $.ajax = remote;
    var ajax = {
        remote: remote
    };
    exports('ajax', ajax);
});